<template>
  <transition
      :appear="true"
      name="animate__animated animate__bounce"
      enter-active-class="animate__swing"
      leave-active-class="animate__backOutUp">
    <li>
      <label >
        <!--    :checked="todo.done" 动态绑定（初始化显示）        @clcick 和 @change 都可以-->
        <input type="checkbox" :checked="todo.done" @click="handleCheck(todo.id)"/>
        <span v-show="!todo.isEdit">{{todo.title}}</span>

        <input ref="inputTitle" :value="todo.title" v-show="todo.isEdit" @blur="handleBlur(todo,$event)">
      </label>

      <button class="btn btn-danger" @click="handleDelete(todo.id)">删除</button>
      <button v-show="!todo.isEdit" class="btn btn-edit" @click="handleEdit(todo)">编辑</button>
    </li>
  </transition>


</template>

<script>
import 'animate.css'
import pubsub from "pubsub-js";

export default {
  // eslint-disable-next-line vue/multi-word-component-names
  name: "Item",
  //声明接受todo
  props:['todo','deleteTodo'],
  methods:{
    handleCheck(id){
    //  通知App组件 各位的done值取反
      console.log(id)
      this.$bus.$emit('checkTodo',id)
    },
    //删除
    handleDelete(id){
      if(confirm('确定删除吗')){
        pubsub.publish('deleteTodos',id)
      }
    },
    //编辑
    handleEdit(todo){
      //hasOwnProperty 监测身上是否有什么属性
      // eslint-disable-next-line no-prototype-builtins
      if(todo.hasOwnProperty('isEdit')){
        todo.isEdit = true
      }else {
        this.$set(todo,'isEdit',true)
      }
      //因为有v-show，则获取不了焦点，可以包一个定时器，也可用$nextTick
      this.$nextTick(function (){
      //  进行的回调会在所有的代码都执行完毕在执行
        this.$refs.inputTitle.focus()
      })
      //定时器写法,不设置时间
      setTimeout(()=>{
        this.$refs.inputTitle.focus()
      })
      // this.$refs.inputTitle.focus()
      //添加编辑状态
      // todo.isEdit = true 这样不行，没有匹配get，set
      // 用set才能实现更改响应式
      // this.$set(todo,'isEdit',true)
    },
    //失去焦点 真正执行修改逻辑
    // $event 对象
    handleBlur(todo,e){
      todo.isEdit = false
      if(!e.target.value.trim()) return alert('输入不能为空')
      this.$bus.$emit('updata',todo.id,e.target.value)
    }
  }



}
</script>

<style scoped>
/*item*/
li {
  list-style: none;
  height: 36px;
  line-height: 36px;
  padding: 0 5px;
  border-bottom: 1px solid #ddd;
}

li label {
  float: left;
  cursor: pointer;
}

li label li input {
  vertical-align: middle;
  margin-right: 6px;
  position: relative;
  top: -1px;
}

li button {
  float: right;
  display: none;
  margin-top: 3px;
}

li:before {
  content: initial;
}

li:last-child {
  border-bottom: none;
}

li:hover{
  background-color: #ddd;
}
li:hover button{
  display: block;
}

</style>